<template>

  <div class="demo-form-top">
    <div class="demo-input-size">
      <label style="margin-right: 10px;">车型编号 </label>
      <el-input
          style="width: 200px"
          v-model="input1"
          class="w-50 m-2"
          size="large"
          placeholder="请输入车型编号搜索"
          :suffix-icon="Search"
      />
    </div>
    <div class="demo-input-size">
      <label style="margin-right: 10px;">关键字</label>
      <el-input
          style="width: 200px"
          v-model="input2"
          class="w-50 m-2"
          size="large"
          placeholder="请输入关键字搜索"
          :suffix-icon="Search"
      />
    </div>
    <div class="demo-input-size">
      <label style="margin-right: 10px;">状态 </label>
      <el-select v-model="selectStatus" placeholder="筛选状态"  size="large">
        <el-option :key="1" label="正常" :value="1"></el-option>
        <el-option :key="0" label="暂停" :value="0"></el-option>
      </el-select>
    </div>

    <div class="demo-button-size">
      <el-button type="primary" @click="getGoodsList">搜索</el-button>
    </div>
    <div class="demo-button-size">
      <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
        <template #reference>
          <el-button type="danger"  :disabled="delBtlStatu">批量删除</el-button>
        </template>
      </el-popconfirm>
    </div>
  </div>


  <div class="demo-table-size">
    <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        tooltip-effect="dark"
        stripe
        border
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"  />
      <el-table-column property="vehNum" label="车型编号" align="center" />
      <el-table-column property="headImg" label="展示图" align="center">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="baseUrl+scope.row.headImg"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column property="heading" label="主标题" width="120" align="center" show-overflow-tooltip  />
      <el-table-column property="subtitle" label="副标题" align="center" show-overflow-tooltip />
      <el-table-column property="price" label="单位价格(日)" align="center" />
      <el-table-column property="sizes" label="该车型总库存" width="120px" align="center" >
        <template #default="scope">
          {{scope.row.sizes==null?0:scope.row.sizes}}
        </template>
      </el-table-column>
      <el-table-column property="useSizes" label="已租借数量" align="center" >
        <template #default="scope">
          {{scope.row.useSizes==null?0:scope.row.useSizes}}
        </template>
      </el-table-column>
      <el-table-column property="status" label="状态" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              class="switchClass"
              :active-value="1"
              :inactive-value="0"
              @change="changeFlagMoney(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column property="blurb" label="简介" align="center" show-overflow-tooltip />
      <el-table-column property="icon"  align="center" width="200" label="操作">
        <template #default="scope">
          <el-button type="primary"  @click="editHandle(scope.row.id)" >编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="这是一段内容确定删除吗？" @click="delHandle(scope.row.id)"   @confirm="">
            <template #reference>
              <el-button type="danger"  >删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>
    <div style="margin-top: 15px;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="float: right;margin-right: 30px"
          small
          background
          :page-sizes="[5, 10, 20, 30]"
          v-model:total="pageParam.total"
          layout="total, sizes, prev, pager, next"
          class="mt-4"
          v-model:current-page="pageParam.current"
          v-model:page-size="pageParam.size"
      />


    </div>
  </div>

  <!--编辑对话框-->
  <el-dialog
      :title="dialogName"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose">

    <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="editForm"  >

      <el-form-item label="主标题" prop="heading" label-width="80px">
        <el-input  v-model="editForm.heading" ></el-input>
      </el-form-item>
      <el-form-item label="副标题" prop="subtitle" label-width="80px">
        <el-input  v-model="editForm.subtitle" ></el-input>
      </el-form-item>
      <el-form-item label="展示图"  prop="headImg" label-width="100px">
        <UploadUtil  v-model="editForm.headImg" :message="parentMessage"  @childEvent="handleChildEvent2" />
      </el-form-item>
      <el-form-item label="单位价格"  prop="price" label-width="100px">
        <el-input-number v-model="editForm.price" :min="1" :max="10000000" />
      </el-form-item>

      <el-form-item label="简介"  prop="blurb" label-width="100px">
        <el-input  v-model="editForm.blurb"  :autosize="{ minRows: 5, maxRows: 15}"  type="textarea"  autocomplete="off"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
    </div>
    <el-form-item  prop="vehId" >
      <el-input type="hidden" v-model="editForm.vehId" ></el-input>
    </el-form-item>
    <el-form-item  prop="vehNum" >
      <el-input type="hidden" v-model="editForm.vehNum" ></el-input>
    </el-form-item>
  </el-dialog>



</template>
<script setup>


import {Search} from "@element-plus/icons-vue";
import {inject, nextTick, onMounted, reactive, ref} from "vue";
import UploadUtil from "@/components/UploadUtil.vue";
import { ElMessage } from 'element-plus';
import axios from "@/axios.js"

const baseUrl = '../../public/img/'



const input1 = ref('')
const input2 = ref('')
const selectStatus = ref('')

onMounted(()=>{
  getGoodsList()
})

const pageParam = ref({
  current:1,
  total:10,
  size:5
})

//分页查询
const getGoodsList = ()=>{
  axios.get(`/goods/list`,{
    params: {
      status:selectStatus.value,
      vehNum:input1.value,
      name: input2.value,
      current: pageParam.value.current,
      size: pageParam.value.size
    }
  }).then(res=>{
    count.value++;
    tableData.value = res.data.records
    pageParam.value.current = res.data.current
    pageParam.value.total= res.data.total
    pageParam.value.size = res.data.size
  })
}

const handleSizeChange = (val)=>{
  console.log(`每页 ${val} 条`)
  pageParam.value.size = val
  getGoodsList()
}
const handleCurrentChange = (val)=>{
  console.log(`当前页: ${val}`)
  pageParam.value.current = val
  getGoodsList()
}


const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  console.log("勾选")
  console.log(val)
  multipleSelection.value = val
  delBtlStatu.value = val.length==0
}
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach(row => {
      multipleTableRef.value.toggleRowSelection(row)
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
}

const delBtlStatu = ref(true)

//删除/批量删除
const delHandle = (id) => {

  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach(row => {
      ids.push(row.id)
    })
  }
  console.log(ids)

  axios.post("/goods/delete", ids).then(res => {
    ElMessage({
      showClose: true,
      message: '恭喜你，删除成功',
      type: 'success',
      onClose: () => {
        getGoodsList() // 在消息关闭时调用getBrandList方法
      }
    });
  })
}


const tableData = ref(
    [
      {


      }
    ]
)

//图片上传部分
const handleChildEvent2 = (data) => {
  console.log('Received from child: ' + data);
  parentMessage.value = data
  editForm.value.headImg = parentMessage
};
const parentMessage = ref('');



//新增/编辑
const dialogVisible = ref(false)
const handleClose = ()=>{
  dialogVisible.value = false
  parentMessage.value= ""
  editForm.value = ref({})
}
const editForm = ref({


})


const ruleFormRef = ref(null)
const rules = reactive({
  heading: [{ required: true, message: '主标题不能为空', trigger: 'blur' }],
  subtitle: [{ required: true, message: '副标题不能为空', trigger: 'blur' }],
  headImg: [{ required: true, message: '展示图不能为空', trigger: 'change' }],
  price: [{ type: 'number', required: true, message: '单位价格必须为数字且不能为空', trigger: 'blur' }],
  unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  sizes: [{ type: 'number', required: true, message: '最大租借数量必须为数字且不能为空', trigger: 'blur' }],
});
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(editForm.value)
      axios.post('/goods/update', editForm.value)
          .then(res => {

            ElMessage({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                getGoodsList() // 在消息关闭时调用getBrandList方法
              }
            });
            dialogVisible.value =false
            resetForm(formEl)
          })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const editHandle = (id) => {

  axios.get('/goods/info/' + id).then(res => {
    editOpen()
    nextTick(() => {
      editForm.value = res.data
      parentMessage.value = editForm.value.headImg
    })

  })
}

const count = ref(0)
const changeFlagMoney = (row) =>{
    if (count.value <1){
      return
    }
    axios.post("/goods/changeStatus", row).then(res => {
      ElMessage({
        showClose: true,
        message: '修改状态成功',
        type: 'success',
        onClose: () => {
          getGoodsList() // 在消息关闭时调用getBrandList方法
        }
      });

  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  dialogVisible.value = false
  parentMessage.value = ""
  formEl.resetFields()
}

const dialogName = ref("")

const editOpen = ()=>{
  dialogName.value = "编辑"
  dialogVisible.value = true
}



</script>


<style scoped>
.demo-form-top{

}

.demo-button-size{
  float: left;
  display: flex;
  align-items: center;
  margin-top: 5px;
  margin-left: 7px;
}

.demo-input-size{
  float: left;
  width: 300px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.demo-table-size{

  margin-top: 20px;
}

.dialog-footer{
  margin-left: 100px;
}


</style>
<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-table__header thead th {
  background-color: #F5F7FA!important;
}

</style>